package com.kacheong.pms.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kacheong.pms.POJO.PageBean;
import com.kacheong.pms.Value.StaticValue;
import com.kacheong.pms.dao.*;
import com.kacheong.pms.domain.*;
import com.kacheong.pms.service.IServeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/service")
public class ServiceController {

    @Autowired
    private ILocationDao locationDao;

    @Autowired
    private IAdvertisementDao advertisementDao;

    @Autowired
    private IRoleDao roleDao;

    @Autowired
    private IMaintainTypeDao maintainTypeDao;

    @Autowired
    private IUserDao userDao;

    @Autowired
    private IMaintainDao maintainDao;

    @Autowired
    private IServeService serveService;

    @RequestMapping("/getMaintainTypes")
    public JSONArray getMaintainTypes(@RequestBody Map<String,Object> params){
        String page = (String) params.get("page");
        Integer currentPage = (Integer) params.get("currentPage");
        PageBean pageBean = null;
        String hql = "FROM MaintainType";
        if (page.equals("1")){
            pageBean = maintainTypeDao.doPage(hql,currentPage,10);
        }
        else if (page.equals("2")){
            pageBean = maintainTypeDao.doPage(hql,1,100);
        }
        return getMaintainTypes(pageBean);
    }

    @RequestMapping("/searchMaintainTypes")
    public JSONArray searchMaintainTypes(@RequestBody Map<String,Object> params){
        String content = (String) params.get("content");
        Integer currentPage = (Integer) params.get("currentPage");
        if (content!=null){
            String hql = "FROM MaintainType m WHERE m.type like '%"+content+"%'" ;
            PageBean pageBean = maintainTypeDao.doPage(hql,currentPage,10);
            return getMaintainTypes(pageBean);
        }
        return null;
    }


    @RequestMapping("/addMaintainType")
    public JSONObject addMaintainType(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        String type = (String) params.get("type");
        if (type!=null&&!type.equals("")){
            MaintainType maintainType = new MaintainType();
            maintainType.setType(type);
            maintainTypeDao.save(maintainType);
            jsonObject.put("msg", StaticValue.success);
        }
        return jsonObject;
    }

    @RequestMapping("/delMaintainType")
    public JSONObject delMaintainType(@RequestBody Map<String,Object> params){
        String type= (String) params.get("info");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg",null);
        String result = serveService.delMaintainType(type);
        jsonObject.put("msg",result);
        return jsonObject;
    }

    @RequestMapping("/editMaintainType")
    public JSONObject editMaintainType(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        Integer id = (Integer) params.get("id");
        String type = (String) params.get("name");
        String result = serveService.editMaintainType(id,type);
        jsonObject.put("msg",result);
        return jsonObject;
    }

    @RequestMapping("/addMaintain")
    public JSONObject addMaintain(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        String plate = (String) params.get("plate");
        String type = (String) params.get("type");
        String name = (String) params.get("name");
        String tel = (String) params.get("tel");
        String info = (String) params.get("info");
        Double cost = Double.parseDouble((String) params.get("cost"));
        if (plate!=null&&!plate.equals(""))
            if (type!=null&&!type.equals(""))
                if (name!=null&&!name.equals("")){
                    jsonObject.put("msg",StaticValue.success);
                    Maintain maintain = new Maintain();
                    maintain.setPlate(plate);
                    maintain.setMaintainType(maintainTypeDao.getBytype(type));
                    maintain.setInfo(info);
                    if (userDao.getByName(name)!=null){
                        User user = userDao.getByName(name);
                        if (user.getTel().equals(tel))
                            maintain.setUser(user);
                        else
                        {
                            user.setTel(tel);
                            userDao.save(user);
                            maintain.setUser(user);
                        }
                    }
                    else {
                        User user = new User();
                        user.setName(name);
                        user.setTel(tel);
                        user.setRole(roleDao.get(2));
                        userDao.save(user);
                        maintain.setUser(user);
                    }
                    maintain.setCreateTime(new Date());
                    maintain.setCost(cost);
                    maintainDao.save(maintain);
                }
        return jsonObject;
    }

    @RequestMapping("/advertisement")
    public JSONObject advertisement(HttpServletRequest request){
        JSONObject jsonObject = new JSONObject();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        String path = request.getSession().getServletContext().getRealPath("/advertisement");
        try {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                MultipartFile mf = entity.getValue();
                //获取该文件的文件名
                String oldFileName = mf.getOriginalFilename();
                String newFileName = UUID.randomUUID().toString().replaceAll("-", "") +
                        oldFileName.substring(oldFileName.lastIndexOf("."));
                File file = new File(path + "/" + newFileName);
                mf.transferTo(file);
                file.mkdir();
                jsonObject.put("fileName",newFileName);
            }
            jsonObject.put("msg",StaticValue.success);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    @RequestMapping(value = "addAdvertisement")
    public JSONObject addAdvertisement(@RequestBody Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        String location = (String) params.get("location");
        String name = (String) params.get("name");
        String tel = (String) params.get("tel");
        Double cost = Double.parseDouble((String) params.get("cost"));
        String fileName = (String) params.get("fileName");
        Integer month = new Integer((String) params.get("month"));
        User user;
        Advertisement advertisement = new Advertisement();
        if (name!=null&&tel!=null)
            if (userDao.getByName(name)!=null){
                user = userDao.getByName(name);
                if (!tel.equals(user.getTel()))
                {
                    user.setTel(tel);
                    userDao.update(user);
                    advertisement.setUser(user);
                }
            }
            else {
                user = new User();
                user.setRole(roleDao.get(2));
                user.setName(name);
                user.setTel(tel);
                userDao.save(user);
                advertisement.setUser(user);
            }
        if (location!=null&&cost!=0&&month!=0){
            advertisement.setCreateTime(new Date());
            advertisement.setAdURL(fileName);
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)+month);
            Date date = calendar.getTime();
            advertisement.setEndTime(date);
            advertisement.setCost(cost);
            Location location1 =locationDao.getByName(location);
            location1.setAdvertisement(advertisement);
            advertisementDao.save(advertisement);
            locationDao.update(location1);
            jsonObject.put("msg",StaticValue.success);
        }
        return jsonObject;
    }

    private JSONArray getMaintainTypes(PageBean pageBean){
        JSONArray jsonArray = new JSONArray();
        List list = pageBean.getList();
        for (Object aList : list) {
            MaintainType maintainType = (MaintainType) aList;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", maintainType.getId());
            jsonObject.put("type", maintainType.getType());
            jsonObject.put("total",pageBean.getAllRow());
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }
}
